﻿using BillsForRazorPages.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BillsForRazorPages.Pages.Bills
{
    public class IndexModel : PageModel
    {
        private readonly BillsForRazorPages.Data.BillsForRazorPagesContext _context;

        public IndexModel(BillsForRazorPages.Data.BillsForRazorPagesContext context)
        {
            _context = context;
        }

        //

        public IList<Bill> Bill { get; set; }

        [BindProperty(SupportsGet = true)]
        public string SearchString { get; set; }

        public SelectList Categories { get; set; }

        [BindProperty(SupportsGet = true)]
        public string BillCateGory { get; set; }

        public async Task OnGetAsync()
        {
            IQueryable<string> genreQuery = from m in _context.Bill
                                            orderby m.Category
                                            select m.Category;
            //LINQ语法，得到对应模型中所有的数据映射
            var bills = from m in _context.Bill
                        select m;
            if (!string.IsNullOrEmpty(SearchString))
            {
                // LINQ查询，Where作用为筛选，本句返回包含查询字段的数据
                bills = bills.Where(s => s.Content.Contains(SearchString));
            }
            if (!string.IsNullOrEmpty(BillCateGory))
            {
                bills = bills.Where(c => c.Category == BillCateGory);
            }


            Categories = new SelectList(await genreQuery.Distinct().ToListAsync());
            Bill = await bills.ToListAsync();
        }
    }
}
